package com.jsmtr.rms.controller.DUserResume;

import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonMapFormatVisitor;
import com.jsmtr.rms.entity.*;
import com.jsmtr.rms.service.IDoResumeService;
import com.jsmtr.rms.service.IProjectService;
import com.jsmtr.rms.service.IResumeService;
import com.jsmtr.rms.service.IUtilService;
import com.jsmtr.rms.service.impl.ResumeService;
import com.jsmtr.rms.utils.CardNoTools;
import com.jsmtr.rms.utils.DateTools;
import com.jsmtr.rms.utils.StringTools;
import com.jsmtr.rms.utils.WordHelper.WordByFreeMarker;
import com.jsmtr.rms.utils.ZipUtils;
import net.sf.json.JSONArray;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping("/AppendOut")
public class AppendOutController {

    @Resource
    private IUtilService utilService;

    @Resource
    private IDoResumeService doResumeService;

    @Resource
    private IProjectService projectService;

    @Resource
    private ResumeService resumeService;


  //  private String headPath;

   // private String savePath;

    @RequestMapping(value = "/OutputByWord")
    public void OutputByWord(HttpServletRequest request, HttpServletResponse response){
       response.setHeader("Access-Control-Allow-Origin","*");
        try {
            String[] ids = request.getParameterValues("id");//人员信息ID
            String type = request.getParameter("type").trim();//招聘流程ID
            String strs = "";
            int num = 0;
            if (ids != null) {
              /*  Properties pps = new Properties();
                pps.load(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("FilePath.properties"), "GBK"));
                this.headPath=pps.getProperty("headpath");*/
                for (String id : ids) {
                    //HRUsers usr = utilService.getSessionUser(request);
                     //id="6bb34471-2c7c-4eed-ba82-b75f00594edb";
                    DUserResume dUserResume= doResumeService.getDUserResume(id);
                  //  this.savePath=pps.getProperty("serverpath");
                    //String headPath="F:/tomcat_ZPQT/webapps/myHrWeb/";
                    //String headPath="D:/开投集团招聘系统/myHrWeb/out/artifacts/myHrWeb_Web_exploded/";
                    String savePath=request.getSession().getServletContext().getRealPath("/resources/ResumeAppends/"+dUserResume.getName()+dUserResume.getCardno()+"/");
				//	savePath=savePath+"resources/ResumeAppends/"+dUserResume.getName()+dUserResume.getCardno()+"/";
                    //String headPath=request.getSession().getServletContext().getRealPath("/resources/UserHead/");

                   /* BaseConfig baseConfig = doResumeService.getBaseConfig("path");
                    String headPath=baseConfig.getCont();*/
                    //String headPath="";
                    Properties pps = new Properties();
                    pps.load(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("FilePath.properties"), "UTF-8"));
                    String headPath=pps.getProperty("headpath");
                    createWordReusme(dUserResume,savePath,headPath);
                    if (type.equals("1")){
                        strs +=  "/resources/ResumeAppends/"+dUserResume.getName()+dUserResume.getCardno()+"/"+dUserResume.getName()+"个人简历.doc,";
                    }else {
                        strs =  "/resources/ResumeAppends/"+dUserResume.getName()+dUserResume.getCardno()+"/"+dUserResume.getName()+"个人简历.doc";
                    }
                    num++;
                  //  utilService.printJsonResult(true,"操作成功","/resources/ResumeAppends/"+dUserResume.getName()+dUserResume.getCardno()+"/"+dUserResume.getName()+"个人简历.doc",response);
                  //  return;
                }
            }
            if(num == ids.length){
                utilService.printJsonResult(true,"操作成功！",strs,response);
            }else
                utilService.printJsonResult(false,"操作失败！","",response);
            return;
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void  createWordReusme(DUserResume dUserResume,String savePath,String headPath) throws Exception {

            String rid=dUserResume.getId();
            Map resumeMap=new HashMap<>();
            ProjectInfoJobs projectInfoJobs=projectService.getProjectInfoJob(dUserResume.getJid());
            UserResume userResume= doResumeService.getUserResume(dUserResume.getCardno());
            resumeMap.put("code",dUserResume.getCode());
            resumeMap.put("name",dUserResume.getName());
            resumeMap.put("sexname",dUserResume.getSexname());
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy.MM");
            resumeMap.put("birthday", sdf.format(dUserResume.getBirthday()));
            resumeMap.put("email",dUserResume.getEmail());
            //String headurl="/resources/UserHead/";
            resumeMap.put("head",headPath+dUserResume.getHead());
            resumeMap.put("tel",dUserResume.getTel());
            resumeMap.put("hometel",dUserResume.getHometel());
            resumeMap.put("mzname",dUserResume.getMzname());
            resumeMap.put("jg",dUserResume.getJg());
            resumeMap.put("zzmmname",dUserResume.getZzmmname());
            resumeMap.put("height",dUserResume.getHeight());
            resumeMap.put("mname",dUserResume.getMname());
            resumeMap.put("distribution",dUserResume.getDistribution()==0?"是":"否");
            resumeMap.put("cardno",dUserResume.getCardno());
            resumeMap.put("jobdepart",(projectInfoJobs.getJobdepart() == null ? "" :projectInfoJobs.getJobdepart()));
            resumeMap.put("jname",dUserResume.getJname());
            resumeMap.put("jdate",dUserResume.getAddDate());
            resumeMap.put("hkname",dUserResume.getHkname());
            resumeMap.put("hukouaddress",dUserResume.getHukouaddress());
            resumeMap.put("nowaddress",dUserResume.getNowaddress());
            resumeMap.put("workexperience",dUserResume.getWorkexperience());
            resumeMap.put("attendancetime",dUserResume.getAttendancetime());
            resumeMap.put("presentsalaryamount",dUserResume.getPresentsalaryamount());
            resumeMap.put("expectedsalaryamount",dUserResume.getExpectedsalaryamount());
            resumeMap.put("posttypename",dUserResume.getPosttypename());
            resumeMap.put("postspecialty",dUserResume.getPostspecialty());
            resumeMap.put("postlevelname",dUserResume.getPostlevelname());
            resumeMap.put("postgettime",dUserResume.getPostgettime());
            resumeMap.put("postcompany",dUserResume.getPostcompany());
            resumeMap.put("qltype",dUserResume.getQltype());
            resumeMap.put("qllevelpname",dUserResume.getQllevelpname());
            resumeMap.put("qllevelname",dUserResume.getQllevelname());
            resumeMap.put("qllevelsname",dUserResume.getQllevelsname());
            resumeMap.put("qlgettime",dUserResume.getQlgettime());
            resumeMap.put("qlorg",dUserResume.getQlorg());
            resumeMap.put("othname",dUserResume.getOthname());
            resumeMap.put("othtypename",dUserResume.getOthtypename());
            resumeMap.put("othzy",dUserResume.getOthzy());
            resumeMap.put("othlevel",dUserResume.getOthlevel());
            resumeMap.put("othcode",dUserResume.getOthcode());
            resumeMap.put("othorg",dUserResume.getOthorg());
            resumeMap.put("introduction",dUserResume.getIntroduction());
            resumeMap.put("englishlevel",userResume.getEnglishLevel());
            resumeMap.put("hobby",userResume.getHobby());
            resumeMap.put("age",userResume.getAge());
            resumeMap.put("mcname",dUserResume.getMname());
            resumeMap.put("birthplace",userResume.getBirthplace());
            resumeMap.put("qq",userResume.getQq());
            resumeMap.put("workdate",userResume.getWorkdate());
            resumeMap.put("mainperformance",userResume.getMainPerformance());
            resumeMap.put("university", userResume.getUniversity());
            resumeMap.put("major", userResume.getMajorname());
            resumeMap.put("educationname",userResume.getEducationname());
            resumeMap.put("degreename", userResume.getDegreeName());
            resumeMap.put("graduate", userResume.getGraduate());
            resumeMap.put("jointime", userResume.getJoinTime());

            /*List<DUserEducation> educations = doResumeService.getUserEducation(rid);//教育背景
            resumeMap.put("edulist",educations);
            List<DUserWorkExperience> workexperiences = doResumeService.getUserWorkExperience(rid); //工作经验
            resumeMap.put("worklist",workexperiences);
            List<DUserTraining> trainings = doResumeService.getUserTraining(rid); //培训经历
            resumeMap.put("trainlist",trainings);
            List<DUserRewardPunishment> rewardpunishments = doResumeService.getUserRewardPunishment(rid); //获奖信息
            resumeMap.put("punishmentlist",rewardpunishments);
            List<DUserFamily> families = doResumeService.getUserFamily(rid);//家庭成员
            resumeMap.put("familylist",families);
            List<UserFamily> majors = doResumeService.getUserFamily1(rid);//家庭成员
            resumeMap.put("majorlist",majors);*/

            List<UserWorkExperience> workexperiences = resumeService.getUserWorkExperience(userResume.getId()); //工作经验
            resumeMap.put("worklist",workexperiences);
            resumeMap.put("worksize",workexperiences.size());

            List<UserTraining> trainings = resumeService.getUserTraining(userResume.getId()); //培训经历
            resumeMap.put("trainlist",trainings);
            List<UserRewardPunishment> rewardpunishments = resumeService.getUserRewardPunishment(userResume.getId()); //获奖信息
            resumeMap.put("punishmentlist",rewardpunishments);
            List<UserFamily> families = resumeService.getUserFamily(userResume.getId());//家庭成员
            resumeMap.put("familylist",families);
            resumeMap.put("familysize",families.size());
            List<UserMajor> majorslist = resumeService.getMajors(userResume.getId());//家庭成员
            resumeMap.put("majorslist",majorslist);
            List<UserEducation> educations = resumeService.getUserEducation(userResume.getId());//教育背景

            List<UserEducation> partEducations = new ArrayList<>();
            for (UserEducation edu: educations) {
                if (edu.getType() == 2) {
                    partEducations.add(edu);
                }
            }

            educations.removeAll(partEducations);
            resumeMap.put("edulist",educations);
            resumeMap.put("edusize",educations.size());
            resumeMap.put("parteducationlist", partEducations);
            WordByFreeMarker word = new WordByFreeMarker();
            // String tempName="DUserResume.ftl";
            //String tempName="个人简历.ftl";
//			String tempName="铁路集团职位申请表.ftl";
        String tempName="应聘人员报名登记.ftl";

            String base64_image=  word.getImageStr(headPath+dUserResume.getHead());
            resumeMap.put("base64_image",base64_image);

            word.createWord(resumeMap,tempName,savePath+"/"+dUserResume.getName()+"个人简历.doc");



    }

    @RequestMapping(value = "/DUserResume/OutputByWordAction")
    public void downZip(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setHeader("Access-Control-Allow-Origin","*");
        /** 下面为下载zip压缩包相关流程 */
        //HttpServletRequest request = ServletActionContext.getRequest();
        FileWriter writer;
        /** 1.创建临时文件夹  */
        try{
        String jobs= request.getParameter("jobs");
        String proid= request.getParameter("proid");
        String rootPath = request.getSession().getServletContext().getRealPath("/resources/upload/");
        String zipName=Long.toString(System.currentTimeMillis());
            BaseUser usr=utilService.getSessionUser(request);
            if (usr==null){
                utilService.printJsonResult(false,"用户登录过期,请重新登录！","/login",response);
            }
            if (StringTools.trimNotEmpty(jobs)){
                zipName=jobs+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            }


        File temDir = new File(rootPath + "/" + zipName);
        if(!temDir.exists()){
            temDir.mkdirs();
        }
        /** 2.生成需要下载的文件，存放在临时文件夹内 */
        // 这里我们直接来10个内容相同的文件为例，但这个10个文件名不可以相同
       /* String[] ids=new String[]{
                "6bb34471-2c7c-4eed-ba82-b75f00594edb","f9663d7c-318e-478f-ac24-88ba653cc760"
        };*/

           /* String paramid = request.getParameter("id");//人员信息ID
            String[] ids=paramid.split(",");*/
            FileOutputStream fos1= new FileOutputStream(new File(rootPath+zipName+".zip"));
            //String headPath="F:/tomcat_ZPQT/webapps/myHrWeb/";
          /*  Properties pps = new Properties();
            pps.load(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("FilePath.properties"), "GBK"));
            this.headPath=pps.getProperty("headpath");
            this.savePath=pps.getProperty("serverpath");*/
            //String headPath="D:/开投集团招聘系统/myHrWeb/out/artifacts/myHrWeb_Web_exploded/";

            //String headPath="F:/tomcat_ZPQT/webapps/myHrWeb/";
            //String headPath="D:/开投集团招聘系统/myHrWeb/out/artifacts/myHrWeb_Web_exploded/";
            String[] ids = request.getParameterValues("id");//人员信息ID
            if (StringTools.trimNotEmpty(jobs)&&ids==null){
                List<DUserResume> dUserResumeList=doResumeService.getDResumeByJob(jobs,proid);

                ids=new String[dUserResumeList.size()];
                for (int i = 0; i < dUserResumeList.size(); i++) {
                    ids[i] = dUserResumeList.get(i).getId();
                }
            }
            if (ids != null) {
            for (String id : ids) {
                //HRUsers usr = utilService.getSessionUser(request);
                DUserResume dUserResume= doResumeService.getDUserResume(id);
                String savePath=request.getSession().getServletContext().getRealPath("/resources/ResumeAppends/"+dUserResume.getName()+dUserResume.getCardno()+"/");
               // String headPath=request.getSession().getServletContext().getRealPath("/resources/UserHead/");
                BaseConfig baseConfig = doResumeService.getBaseConfig("path");
                //String headPath=baseConfig.getCont();
                Properties pps = new Properties();
                pps.load(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("FilePath.properties"), "UTF-8"));
                String headPath=pps.getProperty("headpath");
              //  savePath=savePath+"resources/ResumeAppends/"+dUserResume.getName()+dUserResume.getCardno()+"/";
               // savePath=request.getSession().getServletContext().getRealPath("/resources/ResumeAppends/"+dUserResume.getName()+dUserResume.getCardno()+"/");
                String frompath=pps.getProperty("serverpath")+dUserResume.getName()+dUserResume.getCardno()+"/";
                copyDir(frompath,savePath);
                createWordReusme(dUserResume,savePath,headPath);
                copyDir(savePath,temDir.getPath()+"/"+dUserResume.getName()+dUserResume.getCardno()+"/");

                Duserremark duserremark=new Duserremark();

                duserremark.setRid(dUserResume.getId());
                duserremark.setCardno(dUserResume.getCardno());
                duserremark.setPid(dUserResume.getProid());
                duserremark.setFid(dUserResume.getFid());
                duserremark.setRname(dUserResume.getName());

                List<Duserremark> duserremarkList=utilService.getDuserremark(duserremark);
                if (duserremarkList.size()<=0){
                    duserremark.setId(UUID.randomUUID().toString());
                    duserremark.setAddtime(DateTools.toLenStr(new Date()));
                    duserremark.setAdduser(usr.getUname());
                    duserremark.setAddusercode(usr.getUcode());
                    duserremark.setContent("已下载简历");
                    utilService.addObject(duserremark);
                }else{
                    Duserremark   uduserremark=duserremarkList.get(0);
                    uduserremark.setContent(duserremark.getContent());
                    uduserremark.setEdittime(DateTools.toLenStr(new Date()));
                    uduserremark.setEdituser(usr.getUname());
                    uduserremark.setEditusercode(usr.getUcode());
                    uduserremark.setContent("已下载简历");
                    utilService.editObject(uduserremark);
                }


            }
        }

            ZipUtils.toZip(temDir.getPath(), fos1,true);
            temDir.delete();
            utilService.printJsonResult(true,"操作成功","/resources/upload/"+zipName+".zip",response);
            //downloadFile(rootPath,zipName+".zip",response);

        /** 3.设置response的header */
        //response.setContentType("application/zip");
        //response.setHeader("Content-Disposition", "attachment; filename="+zipName+".zip");
        /** 4.调用工具类，下载zip压缩包 */
        // 这里我们不需要保留目录结构
        //ZipUtils.toZip(temDir.getPath(), response.getOutputStream(),true);
        /** 5.删除临时文件和文件夹 */
        // 这里我没写递归，直接就这样删除了
       /* File[] listFiles = temDir.listFiles();
        for (int i = 0; i < listFiles.length; i++) {
            listFiles[i].delete();
        }
        */
        }catch (Exception e){
            e.printStackTrace();
        }
    }



    /**
     * 以压缩文件导出
     *
     * @param fileName
     * @param filePath
     * @param response
     */
    public void downloadFile(String filePath, String fileName, HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        try {
            File file = new File(filePath, fileName);
            // 以流的形式下载文件。
            BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            // 清空response
            response.reset();
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
//           OutputStream toClient= response.getOutputStream();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setHeader("Access-Control-Allow-Origin", "*");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
            fis.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 复制目录
     * @param fromDir
     * @param toDir
     * @throws IOException
     */
    public static void copyDir(String fromDir,String toDir) throws IOException{
        //创建目录的File对象
        File dirSouce = new File(fromDir);
        //判断源目录是不是一个目录
        if (!dirSouce.isDirectory()) {
            //如果不是目录那就不复制
            return;
        }
        //创建目标目录的File对象
        File destDir = new File(toDir);
        //如果目的目录不存在
        if(!destDir.exists()){
            //创建目的目录
            destDir.mkdir();
        }
        //获取源目录下的File对象列表
        File[]files = dirSouce.listFiles();
        for (File file : files) {
            //拼接新的fromDir(fromFile)和toDir(toFile)的路径
            String strFrom = fromDir + File.separator + file.getName();
            //System.out.println(strFrom);
            String strTo = toDir + File.separator + file.getName();
            //System.out.println(strTo);
            //判断File对象是目录还是文件
            //判断是否是目录
            if (file.isDirectory()) {
                //递归调用复制目录的方法
                copyDir(strFrom,strTo);
            }
            //判断是否是文件
            if (file.isFile()) {
                //System.out.println("正在复制文件："+file.getName());
                //递归调用复制文件的方法
                copyFile(strFrom,strTo);
            }
        }
    }
    /**
     * 复制文件
     * @param fromFile
     * @param toFile
     * @throws IOException
     */
    public static void copyFile(String fromFile,String toFile) throws IOException{
        //字节输入流——读取文件
        FileInputStream in = new FileInputStream(fromFile);
        //字节输出流——写入文件
        FileOutputStream out = new FileOutputStream(toFile);
        //把读取到的内容写入新文件
        //把字节数组设置大一些   1*1024*1024=1M
        byte[] bs = new byte[1024*1024];
        int count = 0;
        while((count = in.read(bs))!=-1){
            out.write(bs,0,count);
        }
        //关闭流
        in.close();
        out.flush();
        out.close();
    }

}
